import { _decorator, Component, Node, director, Label, UITransform } from 'cc';
import { GameEvent, GameManager } from './GameManager';

const { ccclass, property } = _decorator;

@ccclass('CoinManager')
export class CoinManager extends Component {
    private flipDuration = 2;
    private faceNode!: Node;
    private backNode!: Node;
    private isCooling = false;
    private gameManager!: Node;
    private flipTextNode!: Node;
    private flipLabel!: Label;

    onLoad() {
        this.faceNode = this.node.getChildByName("face")!;
        this.backNode = this.node.getChildByName("back")!;
        this.faceNode.active = true;
        this.backNode.active = false;
        this.initFlipTextNode();
    }

    // 初始化文字节点：跟随硬币位置+优化样式
    private initFlipTextNode() {
        this.flipTextNode = this.node.getChildByName("flipText");
        if (!this.flipTextNode) {
            this.flipTextNode = new Node("flipText");
            this.node.addChild(this.flipTextNode); // 作为硬币子节点，自动跟随位置

            // 添加UITransform确保文字排版正常
            const uiTransform = this.flipTextNode.addComponent(UITransform);
            uiTransform.setContentSize(200, 40); // 适配文字长度

            this.flipLabel = this.flipTextNode.addComponent(Label);
            this.flipLabel.fontSize = 15;
            this.flipLabel.color.set(255, 255, 255);
            this.flipLabel.horizontalAlign = Label.HorizontalAlign.CENTER; // 水平居中
            this.flipLabel.verticalAlign = Label.VerticalAlign.CENTER; // 垂直居中
            this.flipLabel.string = "";
        } else {
            this.flipLabel = this.flipTextNode.getComponent(Label)!;
        }

        // 调整文字位置（在硬币正下方，可按需修改偏移量）
        this.flipTextNode.setPosition(0, -this.node.getComponent(UITransform)?.height +45);
        this.flipTextNode.active = false;
    }

    start() {
        this.node.on(Node.EventType.TOUCH_END, this.onCoinClick, this);
        this.gameManager = director.getScene().getChildByName("Canvas").getChildByName("GameManager");
        if (this.gameManager) {
            this.fetchInitialConfig();
            this.gameManager.on(GameEvent.CONFIG_LOADED, this.onConfigLoaded, this);
            this.gameManager.on(GameEvent.GAME_RESET, this.onGameReset, this);
        } else {
            console.error("CoinManager: 未找到GameManager节点！");
        }
    }

    private fetchInitialConfig() {
        if (this.gameManager) {
            const gameManagerComp = this.gameManager.getComponent("GameManager") as GameManager;
            if (gameManagerComp) {
                this.flipDuration = gameManagerComp.flipDuration;
            }
        }
    }

    private onConfigLoaded(config: any) {
        if (config && typeof config.flipDuration !== 'undefined') {
            this.flipDuration = config.flipDuration;
        }
    }

    private onCoinClick() {
        if (this.isCooling) return;

        // 隐藏硬币，显示翻转中文字
        this.flipTextNode.active = true;
        this.startTextFlip();

        this.isCooling = true;

        setTimeout(() => {
            const showFace = Math.random() > 0.5;
            const resultNodeName = showFace ? this.faceNode.name : this.backNode.name;

            // 显示结果文字（停留0.8秒后隐藏）
            this.flipLabel.string = `${resultNodeName}`;
            this.flipLabel.color.set(0, 0, 0); 

            setTimeout(() => {
                // 隐藏文字，显示硬币结果
                this.flipTextNode.active = false;
                this.faceNode.active = showFace;
                this.backNode.active = !showFace;

                this.node.emit("flip_result", showFace);
                this.isCooling = false;
            }, 500); // 结果文字显示时长，可调整
        }, this.flipDuration * 1000);
    }

    // 翻转过程文字（可添加简单动画感）
    private startTextFlip() {
        this.flipLabel.string = "翻转中...";
        this.flipLabel.color.set(255, 255, 255); // 白色翻转文字

        // 可选：添加文字闪烁效果增强体验
        let isBright = true;
        const flashTimer = setInterval(() => {
            this.flipLabel.color.set(isBright ? 255 : 150, isBright ? 255 : 150, isBright ? 255 : 150);
            isBright = !isBright;
        }, 300);

        // 翻转结束后清除闪烁定时器
        setTimeout(() => {
            clearInterval(flashTimer);
        }, this.flipDuration * 1000);
    }

    private stopTextFlip() {
        this.flipTextNode.active = false;
    }

    private onGameReset() {
        this.stopTextFlip();
        this.faceNode.active = true;
        this.backNode.active = false;
        this.isCooling = false;
    }

    onDestroy() {
        this.stopTextFlip();
        this.node.off(Node.EventType.TOUCH_END, this.onCoinClick, this);
        if (this.gameManager) {
            this.gameManager.off(GameEvent.CONFIG_LOADED, this.onConfigLoaded, this);
            this.gameManager.off(GameEvent.GAME_RESET, this.onGameReset, this);
        }
    }
}